package com.xxl.job.xxljob;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.xxl.job.annotation.XxlJobRegister;
import com.xxl.job.feign.XxlJobAdminRpc;
import com.xxl.job.feign.domain.XXlJobInfoPage;
import com.xxl.job.feign.domain.XxlJobStopRun;
import com.xxl.job.feign.response.ReturnT;
import com.xxl.job.xxljob.domain.XxlJobInfo;
import com.xxl.job.xxljob.domain.XxlJobTokenInfo;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @classname XxlJobRegisterConfiguration
 * @description [  启动xxl job的注册 ]
 * @date 2023/4/5 17:00
 */
@Slf4j
public class XxlJobRegisterConfiguration implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    XxlJobAdminRpc xxlJobAdminRpc;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ConfigurableApplicationContext context = event.getApplicationContext();
        // 要注册的job列表
        List<Job> jobList = new ArrayList<>();
        for (String beanName : context.getBeanDefinitionNames()) {
            final Object bean = context.getBean(beanName);
            final Map<Method, XxlJobRegister> selectMethods = MethodIntrospector.selectMethods(
                    AopUtils.getTargetClass(bean),
                    (MethodIntrospector.MetadataLookup<XxlJobRegister>) method -> AnnotatedElementUtils.findMergedAnnotation(method, XxlJobRegister.class)
            );
            // 解析注解
            for (Method method : selectMethods.keySet()) {
                final XxlJob xxlJob = AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class);
                if (Objects.nonNull(xxlJob)) {
                    final Job job = new Job();
                    job.setJobRegister(selectMethods.get(method));
                    job.setJobId(xxlJob.value());
                    jobList.add(job);
                }else {
                    log.error("没有找到 @XxlJob 注解... @XxlJob + @XxlJobRegister 需要配合使用...");
                }
            }
        }
        if (CollectionUtils.isEmpty(jobList)) {
            log.error("没有获取到任务执行器! 不需要注册定时任务...");
            return;
        }
        // 注册
        registerJob(jobList);
    }

    /**
     * 注册 job
     * @param jobList jobList
     */
    private void registerJob(List<Job> jobList) {
        final XXlJobInfoPage xXlJobInfoPage = new XXlJobInfoPage(
                XxlJobTokenInfo.getInstance().getJobGroupId(), 0, 100, -1
        );
        final Map<String, Object> resultMap = xxlJobAdminRpc.jobInfoPageList(xXlJobInfoPage);
        final List<XxlJobInfo> jobInfos = Optional.ofNullable(resultMap)
                .map(map -> JSON.toJSONString(map.get("data")))
                .map(json -> JSONObject.parseArray(json, XxlJobInfo.class))
                .orElse(new ArrayList<>(2));
        // 直接注册流程
        if (CollectionUtils.isEmpty(jobInfos)) {
            jobList.forEach(this::addJob);
            return;
        }
        final Map<String, List<XxlJobInfo>> xxlJobInfoMap = jobInfos.stream()
                .filter(xxlJobInfo -> !StringUtils.isEmpty(xxlJobInfo.getExecutorHandler()))
                .collect(Collectors.groupingBy(XxlJobInfo::getExecutorHandler));
        // 已经存在的就不需要重新注册了,直接更新一下配置信息
        for (Job job : jobList) {
            if (Objects.isNull(xxlJobInfoMap.get(job.getJobId()))) {
                this.addJob(job);
            }else {
                this.updateJob(job,xxlJobInfoMap.get(job.getJobId()).get(0));
            }
        }
    }

    /**
     * addJob
     * @param job job
     */
    private void addJob(Job job) {
        final XxlJobInfo xxlJobInfo = getXxlJobInfo(job);
        final ReturnT<String> returnT = xxlJobAdminRpc.jobAdd(xxlJobInfo);
        log.warn("JobHandler:" + xxlJobInfo.getExecutorHandler() + ",注册新增结果：" + (returnT.getCode() == 200 ? "SUCCESS" : String.format("FAIL:%s",returnT.getMsg())));
    }

    private XxlJobInfo getXxlJobInfo(Job job) {
        final XxlJobInfo xxlJobInfo = new XxlJobInfo();
        xxlJobInfo.setJobGroup(XxlJobTokenInfo.getInstance().getJobGroupId());
        xxlJobInfo.setExecutorHandler(job.getJobId());
        xxlJobInfo.setScheduleType("CRON");
        xxlJobInfo.setScheduleConf(job.getJobRegister().cron());
        xxlJobInfo.setTriggerStatus(job.getJobRegister().triggerStatus());
        xxlJobInfo.setJobDesc(job.getJobRegister().jobDesc());
        xxlJobInfo.setAuthor(job.getJobRegister().author());
        xxlJobInfo.setExecutorRouteStrategy(job.getJobRegister().routeStrategy());

        // 写新增默认的配置
        xxlJobInfo.setGlueType("BEAN");
        xxlJobInfo.setMisfireStrategy("DO_NOTHING");
        xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");

        return xxlJobInfo;
    }

    /**
     * updateJob
     * @param job job
     * @param xxlJobInfo xxlJobInfo
     */
    private void updateJob(Job job, XxlJobInfo xxlJobInfo) {
        BeanUtil.copyProperties(
                getXxlJobInfo(job),xxlJobInfo,
                CopyOptions.create().ignoreNullValue().setIgnoreError(true)
        );

        // 暂停和启动job
        pauseRunJob(xxlJobInfo);

        final ReturnT<String> returnT = xxlJobAdminRpc.update(xxlJobInfo);
        log.warn("JobHandler:" + xxlJobInfo.getExecutorHandler() + ",注册更新结果：" + (returnT.getCode() == 200 ? "SUCCESS" : String.format("FAIL:%s",returnT.getMsg())));
    }

    private void pauseRunJob(XxlJobInfo xxlJobInfo) {
        if (xxlJobInfo.getTriggerStatus() == 0) {
            pauseJob(xxlJobInfo);
        } else {
            startJob(xxlJobInfo);
        }
    }

    private void pauseJob(XxlJobInfo xxlJobInfo) {
        final XxlJobStopRun xxlJobStop = new XxlJobStopRun(xxlJobInfo.getId());
        final ReturnT<String> returnT = xxlJobAdminRpc.pause(xxlJobStop);
        log.warn("JobHandler:" + xxlJobInfo.getExecutorHandler() + ",暂停任务结果：" + (returnT.getCode() == 200 ? "SUCCESS" : String.format("FAIL:%s",returnT.getMsg())));
    }

    private void startJob(XxlJobInfo xxlJobInfo) {
        final XxlJobStopRun xxlJobStop = new XxlJobStopRun(xxlJobInfo.getId());
        final ReturnT<String> returnT = xxlJobAdminRpc.start(xxlJobStop);
        log.warn("JobHandler:" + xxlJobInfo.getExecutorHandler() + ",启动任务结果：" + (returnT.getCode() == 200 ? "SUCCESS" : String.format("FAIL:%s",returnT.getMsg())));
    }

    @Data
    public static class Job {

        private XxlJobRegister jobRegister;

        private String jobId;

    }

}
